﻿using AutoMapper;
using MediatR;
using Production.CommonLib.Models;
using Production.DomainLib.AggregatesModel.ProductionOrderAggregate;
using Swimj.CommonLib.Base;

namespace Production.ApplicationLib.Command;

public class UpdateProductionOrderCommand: ProductionOrderEditRequestDto, IRequest<Result<ProductionOrderInfoResponseDto>>
{
    public int Id { get; set; }
}

public class UpdateProductionOrderCommandHandler : IRequestHandler<UpdateProductionOrderCommand, Result<ProductionOrderInfoResponseDto>>
{
    private readonly IProductionOrderRepository _productionOrderRepository;
    private readonly IMapper _mapper;

    public UpdateProductionOrderCommandHandler(IProductionOrderRepository productionOrderRepository,
        IMapper mapper)
    {
        _productionOrderRepository = productionOrderRepository;
        _mapper = mapper;
    }

    public async Task<Result<ProductionOrderInfoResponseDto>> Handle(UpdateProductionOrderCommand request, CancellationToken cancellationToken)
    {
        var productionOrder = await _productionOrderRepository.Get(request.Id);
        if (productionOrder != null)
        {
            productionOrder.Update(request.Code, request.Name, request.OrderSource,
                request.OrderStatus,
                request.StandardBom.Id, request.StandardBom.Code, request.StandardBom.Name, request.Quantity,
                request.ExpectedTime, request.EndTime, request.PlanStartTime, request.PlanEndTime, request.Description);
        }

        await _productionOrderRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

        return await Result<ProductionOrderInfoResponseDto>.SuccessAsync(_mapper.Map<ProductionOrderInfoResponseDto>(productionOrder));
    }
}